package com.nach0x.theTVDBrenamer;

import gnu.getopt.Getopt;
import gnu.getopt.LongOpt;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.PrintStream;
import java.util.ArrayList;

/**
 *
 * @author nacho
 */
public class Main {
    
    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
               
        LongOpt[] longopts = new LongOpt[5];
        longopts[0] = new LongOpt("move", LongOpt.NO_ARGUMENT, null, 'm');
        longopts[1] = new LongOpt("copy", LongOpt.NO_ARGUMENT, null, 'c'); 
        longopts[2] = new LongOpt("destiny", LongOpt.REQUIRED_ARGUMENT, null, 'd'); 
        longopts[3] = new LongOpt("help", LongOpt.NO_ARGUMENT, null, 'h'); 
        longopts[4] = new LongOpt("show-errors", LongOpt.NO_ARGUMENT, null, 'e'); 

        boolean remove = false;
        boolean log = true;
        boolean setDestiny = false;
        String invalidOption = null;
        ArrayList<File> files = new ArrayList<File>();
        File destiny = null;
        
        int c;
        Getopt g = new Getopt("theTVDB-Renamer", args, "-cmed:h files", longopts);
        g.setOpterr(false);
        
        while ((c = g.getopt()) != -1)
        {
            switch(c)               
            {
                case 'c':
                    remove = false;
                    break;

                case 'm':
                    remove = true;
                    break;

                case 'd':
                    setDestiny = true;
                    destiny = new File(g.getOptarg());
                    break;
                case 'e':
                    log = false;
                    break;

                case 1:
                    files.add(new File(g.getOptarg()));
                    break;

                case '?':
                    if(g.getOptopt() == (char) 'd')
                        setDestiny = true;
                    else
                        invalidOption = "" + (char) g.getOptopt();
                    break;

                case 'h':
                    showHelp();
                    
                default:
                    showUsage();
                    return;
           }    
       }
        
        PrintStream ps = System.err;
        
        try {
            
            try {
                if(log)
                    ps = new PrintStream(new FileOutputStream(new File("renamer.log")));
                System.setErr(ps);
            } catch (FileNotFoundException ex) {
                System.err.println("Could not load the log file");
            }
            
            if(invalidOption != null)
                throw new Exception("Invalid option -" + invalidOption + ". --help for help");
            
            if(setDestiny)
                if(destiny == null)
                    throw new Exception("The option -d requires an argument. --help for help");
                else if(!destiny.isDirectory())
                    throw new Exception("'" + destiny + "' is not a directory. --help for help");
                else if(!destiny.exists())
                    throw new Exception("'" + destiny + "' does not exist");
            
            if(files.isEmpty())
                throw new Exception("no imput files");
            
            FileTools fileTools = new FileTools();
            Search search = new Search();
            
            for (File file : files) {
                try {
                    EpisodeAtrb ep = fileTools.parseFile(file);
                    
                    search.getEpisodeInfo(ep);
                    
                    String dst;
                    
                    if(!setDestiny)
                        dst = ep.getFile().getParent() + File.separator;
                    else {
                        dst = destiny.getPath() + File.separator;
                        dst += ep.getSeriesName() + File.separator + 
                                "Season " + new Integer(ep.getSeasonNbr()) + File.separator;
                        new File(dst).mkdirs();
                    }
                    
                    dst += ep.getFormatFileName();
                    fileTools.fileCopy2(file, new File(dst));
                    
                } catch(Exception e) {
                    System.err.println(e.getMessage());
                }
            }
            
        } catch(Exception e) {
            System.err.println(getProgramName() + ": " + e.getMessage());
            //System.exit(1);
        }
        return;        
    }
    
    public static String getProgramName() {
        return "theTVDB-Renamer";
    }
    
    public static void showHelp() {
        System.out.println("Renames TV series episodes using theTVDB API and places them in the appropiate folder");
 //       showUsage();
    }
    
    public static void showUsage() {
        String program = getProgramName();
        System.out.println("Use: " + program + " [-cm] [-d folder] file");
        System.out.println("     " + program + " -c,--copy            : makes a copy of the file. Default");
        System.out.println("     " + program + " -m,--move            : moves the file");
        System.out.println("     " + program + " -d,--destiny folder  : especify the folder where the file will be placed");
        System.out.println("     " + program + " -e,--show-errors     : errors will be displayed on the console");
        System.out.println("                                            by default, errors are written in 'renamer.log'");
        System.out.println();
    }
    
}
